package com.feng.stateAnalysis
{
	import com.feng.FengData;
	import com.feng.data.StateData;
	import com.feng.debug.logger;
	import com.feng.utils.PlayerUtils;

	/**
	 * 攻击顺序分析
	 * @author 风之守望者
	 * 2013-4-7
	 */
	public class AttackOrderAnalysis
	{
		private var stateData:StateData;

		public function AttackOrderAnalysis(stateData:StateData)
		{
			this.stateData = stateData;
		}

		/** 计算该轮攻击顺序 */
		public function onTurn(state:Array, myId:int):void
		{
			if (FengData.isDebug && stateData.surplusAttackOrder && stateData.surplusAttackOrder.length > 0)
			{
				logger("【攻击顺序计算错误】");
				logger(stateData.surplusAttackOrder);
			}

			stateData.attackOrder = [];

			var speedSate:Array = state.concat();

			speedSate = speedSate.filter(function(x:*, index:int, arr:Array):Boolean
			{
				return (x.hp > 0);
			});

			speedSate.sort(function(x:*, y:*):Number
			{
				if (x.hp == 0 || y.hp == 0)
					return y.hp - x.hp;
				if (x.spd == y.spd)
					return x.id - y.id;
				return y.spd - x.spd;
			});
			for (var i:int = 0; i < speedSate.length; i++)
			{
				if (speedSate[i].spd == speedSate[0].spd)
				{
					stateData.attackOrder.push(speedSate[i]);
					stateData.attackOrder.push(speedSate[i]);
				}
				else
				{
					stateData.attackOrder.push(speedSate[i]);
				}
			}

			stateData.surplusAttackOrder = stateData.attackOrder.concat();

			stateData.currentAttackerSpeed = stateData.attackOrder[0].spd;
			stateData.attackedList = [];
			stateData.freeAttack = true;

			logger("【该轮攻击顺序】");
			logger(stateData.attackOrder);
		}

		public function onAnyoneAttack(state:Array, myId:int, attackerId:int, targetId:int):void
		{
			for (var j:int = 0; j < stateData.surplusAttackOrder.length; j++)
			{
				if (stateData.surplusAttackOrder[j].id == attackerId)
				{
					//判断是否为下一波攻击
					if (stateData.currentAttackerSpeed != stateData.surplusAttackOrder[j].spd //
						|| (stateData.freeAttack && stateData.attackedList.indexOf(attackerId) != -1))
					{
						stateData.currentSpeedDiePlayers = [];
						stateData.currentSpeedAttackRecord = [];
						stateData.killUpgradePlayers = [];
						stateData.freeAttack = false;
					}
					stateData.currentAttackerSpeed = stateData.surplusAttackOrder[j].spd;

					stateData.surplusAttackOrder.splice(j, 1);
					break;
				}
			}

			//判断是否被击杀
			if (stateData.realState[targetId].hp <= PlayerUtils.attackDamage(stateData.realState[attackerId], stateData.realState[targetId]))
			{
				for (var i:int = stateData.surplusAttackOrder.length - 1; i >= 0; i--)
				{
					if (stateData.surplusAttackOrder[i].id == targetId)
						stateData.surplusAttackOrder.splice(i, 1);
				}
			}
			stateData.attackedList.push(attackerId);

			logger("【剩余攻击玩家】");
			logger(stateData.surplusAttackOrder);
		}
	}
}
